#!/usr/bin/env jython
# coding=utf-8

import os
import sys
import re
import logging
import glob
import codecs

# set log
logFileName = 'CheckLoopbackResult.log'
def init_log():
    logger = logging.getLogger()
    hdlr = logging.FileHandler(logFileName)
    formatter = logging.Formatter('%(asctime)s %(levelname)s:: %(message)s')
    hdlr.setFormatter(formatter)
    logger.addHandler(hdlr)
    logger.setLevel(logging.INFO)
    return logger

log = init_log()

class ItemParseError(Exception): pass

class DicItem:
	def __init__(self, linestr):
		while linestr[-1].isspace():
			linestr = linestr[:-1]
		self._linestr = linestr
		# parse attributes from line string
		# 'Name	PinYin	NextLevelId	NextLevelInfo	Offset VoiceId	NextLevelNumber'
		pat = re.match( \
			r'^(\S+)\t([\w /]+)\t(0x[\dA-F]{8})\t(0x[\dA-F]{8})\t(0x[\dA-F]{8})\t(0x[\dA-F]{8})\t(0x[\dA-F]{4})\s*$', \
			self._linestr)
		if not pat:
			log.warning(r'<DicItem Line Format Error> : %s', self._linestr)
			raise ItemParseError()
		self._name = pat.group(1)
		self._pinyin = pat.group(2)
		self._nextLevelId = pat.group(3)
		self._nextLevelInfo = pat.group(4)
		self._offset = pat.group(5)
		self._voiceId = pat.group(6)
		self._nextLevelNum = pat.group(7)
		#self._attrs = { 
				#1: self._name, 'name': self._name,
				#2: self._pinyin, 'pinyin':self._pinyin,
				#3: self._nextLevelId, 'nextLevelId': self._nextLevelId,
				#4: self._nextLevelInfo, 'nextLevelInfo': self._nextLevelInfo,
				#5: self._offset, 'offset': self._offset,
				#6: self._voiceId, 'voiceId': self._voiceId,
				#7: self._nextLevelNum, 'nextLevelNum': self._nextLevelNum
				#}

	def get_str(self):
		return self._linestr
	
	#@staticmethod
	def _get_from_file(fn):
		lns = codecs.open(fn, 'r', 'gbk').readlines()
		#return tuple(DicItem(ln) for ln in lns)
		return tuple(map(lambda line:DicItem(line), lns))
	get_from_file = staticmethod (_get_from_file)
		
	def __getitem__(self, attr):
		' Return a string.\n'
		#return self._attrs[attr]
		return self.__dict__['_' + attr]

class VrResultItem:
	def __init__(self, linestr):
		while linestr[-1].isspace():
			linestr = linestr[:-1]
		self._linestr = linestr;
		#pat = re.match( \
			#r'^(\S+)\t(\S+)\t(.+\])\s(0x[\dA-F]{8})\t(0x[\dA-F]{8})\t(0x[\dA-F]{8})\t(0x[\dA-F]{8})\t(0x[\dA-F]{8})\s*$', \
			#self._linestr)
		pat = re.search( \
			r'(\S+)\t(.+\])\s(0x[\dA-F]{8})\t(0x[\dA-F]{8})\t(0x[\dA-F]{8})\t(0x[\dA-F]{8})\t(0x[\dA-F]{8})\s*$', \
			self._linestr)
		if not pat:
			log.warning(r'<VrResultItem Line Format Error> : %s', self._linestr)
			raise ItemParseError()
		#self._name = pat.group(1)
		self._vrName = pat.group(1)
		self._dicId = pat.group(3)
		self._nextLevelId = pat.group(4)
		self._nextLevelInfo = pat.group(5)
		self._offset = pat.group(6)
		self._voiceId = pat.group(7)
		
	def get_str(self):
		return self._linestr
	
	#@staticmethod
	def _get_from_file(fn):
		lns = codecs.open(fn, 'r', 'gbk').readlines()
		#return tuple(DicItem(ln) for ln in lns[4:])
		return tuple(map(lambda line:VrResultItem(line), lns[4:]))
	get_from_file = staticmethod(_get_from_file)
		
	def __getitem__(self, attr):
		' Return a string.\n'
		#return self._attrs[attr]
		return self.__dict__['_' + attr]


def compare_vr_result(dicIds, folder):
	ret = []
	for dicId in dicIds:
		ret.append(compare_vr_dic(dicId, folder))
	return ret

def compare_vr_dic(dicId, folder):
	allRight = True
	allWrong = True
	dicItems = DicItem.get_from_file(os.path.join(folder, dicId+'.txt'))
	vrRIs = VrResultItem.get_from_file(os.path.join(folder, dicId+'.out.txt'))
	if len(dicItems) != len(vrRIs) or len(dicItems) == 0:
		log.warning('<VR Length Error> : %s', dic)
		raise Exception()
	for n in range(len(dicItems)):
		itm = dicItems[n]
		vrt = vrRIs[n]
		if vrt['vrName'] != itm['name'] or \
				vrt['dicId'] != '0x' + dicId or \
				vrt['nextLevelId'] != itm['nextLevelId'] or \
				vrt['nextLevelInfo'] != itm['nextLevelInfo'] or \
				vrt['offset'] != itm['offset'] or \
				vrt['voiceId'] != itm['voiceId'] :
			log.warning('<VR Error> : 0x%s : %d : %s : %s', dicId, len(dicItems), itm.get_str(), vrt.get_str())
			allRight = False
		else:
			allWrong = False
	if allRight and not allWrong:
		return 'OK'
	elif not allRight and not allWrong:
		return 'NotGood'
	elif not allRight and allWrong:
		return 'Failed'
	else:
		raise Exception()

def main():
	if len(sys.argv) != 2:
		print('Usage:')
		print('python CheckLoopbackResult.py [ResultFolder]')
		sys.exit(0)
	folder = sys.argv[1]
	fns = tuple(os.path.split(p)[1] for p in  glob.glob(os.path.join(folder, '????????.txt')))
	#dicIds = tuple(fn[:8] for fn in fns)
	dicIds = tuple(map(lambda s:s[:8], fns))
	cr = compare_vr_result(dicIds, folder)
	fo = open('Result.txt', 'w')
	for n in range(len(dicIds)):
		print >> fo, '%s\t%s' % (dicIds[n], cr[n])
	fo.close()
	
	
if __name__ == '__main__':
	main()

	
